<?php

class ItsCustProductSitesController extends AppController {

    var $name = 'ItsCustProductSites';
    var $viewPath = 'its/inventories/its_cust_product_sites';
    var $uses = array('CustProductSite', 'Product', 'Customer', 'Site', 'Period', 'ProductSerial', 'CPSLocation', 'CustLocation', 'CPSPriceHistory');

    function save() {
        $cust_product_site_id = null;
        if (!empty($this->data)) {
            $is_success = true;

            $product_id = $this->data['CustProductSite']['product_id'];
            $this->Product->id = $product_id;
            $supplier_id = $this->Product->field('supplier_id');
            $this->data['CustProductSite']['supplier_id'] = $supplier_id;
            $this->data['CustProductSite']['stock_code'] = strtoupper($this->data['CustProductSite']['stock_code']);

            // ถ้าเป็นการ add Stock code Site Site เดียวกันห้ามซ้ำ
            if (empty($this->data['CustProductSite']['id']) && $this->CustProductSite->hasAny(array('stock_code' => $this->data['CustProductSite']['stock_code'], 'site_id' => $this->data['CustProductSite']['site_id']))) {
                $this->CustProductSite->validationErrors['stock_code'] = 'This Stock code is already taken';
                $is_success = false;
            } else {
                $text = trim($this->data['CustProductSite']['text']);
                $this->data['CustProductSite']['text'] = strlen($text) == 0 ? null : $text;

                $this->Product->id = $this->data['CustProductSite']['product_id'];

                $this->Site->id = $this->data['CustProductSite']['site_id'];
                $this->data['CustProductSite']['customer_id'] = $this->Site->field('customer_id');
                $this->data['CustProductSite']['collector_id'] = $this->Session->read('Auth.User.id');
                $is_success = $this->CustProductSite->save($this->data);
            }

            if ($is_success == true) {
                $this->Session->setFlash("Customer site product stock code {$this->data['CustProductSite']['stock_code']} save succesfull.", 'flash/ok');
                $cust_product_site_id = $this->CustProductSite->id;
            } else {
                $this->Session->setFlash("Customer site product save fail.", 'flash/fail');
            }
        }
        $this->setAction('view', $cust_product_site_id);
        $this->set('hasDiv', false);
    }

    function view($id = null) {
        $this->CustProductSite->contain(array('Product' => array('Unit'), 'Supplier'));
        if (!empty($this->params['named'])) {
            $site_id = $this->params['named']['site_id'];
            $product_id = $this->params['named']['product_id'];

            $this->data = $this->CustProductSite->find('first', array(
                        'conditions' => array('site_id' => $site_id, 'product_id' => $product_id,)
                            )
            );
            if (empty($this->data)) {
                $this->data['CustProductSite']['site_id'] = $site_id;
                $this->data['CustProductSite']['product_id'] = $product_id;
                $this->set('mode', 'add');
            } else {
                $this->set('mode', 'edit');
            }
            $this->Session->write("{$this->name}.site_id", $site_id);   // จำไว้สำหรับ paging neighbors
        } else {
            if ($id != null) {
                $this->data = $this->CustProductSite->findById($id);
                $this->set('mode', 'edit');
            } else {
                $this->set('mode', 'add');
            }
        }

        $this->set('hasDiv', true);
        $this->set('periods', $this->Period->find('list'));

        // ถ้าเป็น Supplier เข้ามาให้เป็นหน้า Supplier view
        if ($this->Auth->user('prefix') == SUPPLIER_PREFIX && $this->Session->read('Auth.User.Extend.from_its_user') == false) {
            $this->render('supplier_view');
        }
    }

    function delete($id = null) {
        $this->CustProductSite->id = $id;
        // ถ้าเคย มีการเคลื่อนไหวสินค้า product นี้แล้วไม่ให้ลบ
        if ($this->ProductSerial->hasAny(array('cust_product_site_id' => $id))) {
            $this->Session->setFlash("Can not delete this product.", 'flash/fail');
            $this->setAction('view', $id);
        } else {
            $this->params['named']['site_id'] = $this->CustProductSite->field('site_id');
            $this->params['named']['product_id'] = $this->CustProductSite->field('product_id');

            if ($this->CustProductSite->delete($id)) {
                $this->Session->setFlash("Customer site product delete succesfull.", 'flash/ok');
                $this->setAction('view');
            } else {
                $this->Session->setFlash("Customer site product delete fail.", 'flash/fail');
                $this->setAction('view', $id);
            }
        }
    }

    function popup_view($id = null) {
        $this->layout = 'popup';
        $this->Product->id = $this->params['named']['product_id'];
        $part_no = $this->Product->field('part_no');
        $this->Customer->id = $this->params['named']['customer_id'];
        $customer = $this->Customer->field('name');
        $this->Site->id = $this->params['named']['site_id'];
        $site = $this->Site->field('name');
        $this->set('popupTitle', 'Please add stock code for ' . $customer . ', ' . $site . ' Part no ' . $part_no);
        $this->set('popupWidth', '800');
        //$this->set('popupPosition', '["top", 50]');
        $this->set('site_id', $this->params['named']['site_id']);
        $this->set('product_id', $this->params['named']['product_id']);
    }

    /**
     * action สำหรับ display location ที่สามารถ stock in ได้สำหรับ CPS นี้
     * @param int $cust_product_site_id
     */
    function display_locations($cust_product_site_id) {
        $this->layout = 'ajax';
        $this->CPSLocation->contain(array('CustLocation'));
        $this->data = $this->CPSLocation->findAllByCustProductSiteId($cust_product_site_id);

        $this->CustProductSite->id = $cust_product_site_id;
        $site_id = $this->CustProductSite->field('site_id');

        // Subquery ดึงรายการ Location ที่อยู่ใน CPSLocation ของ CustProductSite นี้
        $conditionsSubQuery['CPSLocation.cust_product_site_id'] = $cust_product_site_id;
        $dbo = $this->CPSLocation->getDataSource();
        $subQuery = $dbo->buildStatement(
                        array(
                            'fields' => array('CPSLocation.cust_location_id'),
                            'table' => $dbo->fullTableName($this->CPSLocation),
                            'alias' => 'CPSLocation',
                            'conditions' => $conditionsSubQuery,
                            'order' => null, 'limit' => null, 'group' => null,
                        ),
                        $this->CPSLocation
        );
        $subQuery = ' CustLocation.id NOT IN (' . $subQuery . ') ';
        $subQueryExpression = $dbo->expression($subQuery);
        $conditions[] = $subQueryExpression;
        $conditions['site_id'] = $site_id;

        $custLocations = $this->CustLocation->find('list', array('conditions' => $conditions, 'order' => 'CustLocation.name'));

        // ดึงรายการ Location ที่ไม่อยู่ใน CPSLocation นี้
        $this->set('custLocations', $custLocations);
        $this->set('cust_product_site_id', $cust_product_site_id);
    }

    /**
     * บันทึก Location ของ CPS ที่จะ stock in ได้
     */
    function save_location() {
        $this->layout = 'ajax';
        $cust_product_site_id = $this->data['CPSLocation']['cust_product_site_id'];
        $this->CPSLocation->query("BEGIN");
        if ($this->CPSLocation->save($this->data)) {
            $this->CPSLocation->query("COMMIT");
            $this->Session->setFlash("Location save succesfull.", 'flash/ok');
        } else {
            $this->CPSLocation->query("ROLLBACK");
            $this->Session->setFlash("Location save fail.", 'flash/fail');
        }
        $this->setAction('display_locations', $cust_product_site_id);
    }

    /**
     * ลบ Location ของ CPS ที่จะ stock in ได้
     */
    function delete_location($cps_location_id) {
        $this->layout = 'ajax';
        $is_success = false;

        $this->CPSLocation->id = $cps_location_id;
        $cust_product_site_id = $this->CPSLocation->field('cust_product_site_id');

        $is_success = $this->CPSLocation->delete($cps_location_id, true);

        if ($is_success) {
            $this->Session->setFlash("Location delete succesfull.", 'flash/ok');
        } else {
            $this->Session->setFlash("Can not delete this location.", 'flash/fail');
        }
        $this->setAction('display_locations', $cust_product_site_id);
    }

    
    function popup_view_price($id, $cust_view = false) {
        $this->layout = 'popup';

        $this->CustProductSite->id = $id;
        $this->set('popupTitle', 'Price History : ' . $this->CustProductSite->field('stock_code'));
        $this->set('popupWidth', 400);

        $this->data = $this->CPSPriceHistory->find('all', array(
                    'conditions' => array(
                        'cust_product_site_id' => $id,
                    ),
                    'order' => 'created DESC',
                    'contain' => array('User')
                ));
        // ถ้าเป็น Customer view ไม่ต้องโชว์ updated by
        if ($cust_view) {
            $this->render('popup_view_price_cust');
        }
    }

}

?>